package com.draven.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.draven.common.Result;
import com.draven.entity.NoteCategory;
import com.draven.service.NoteCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * 笔记分类控制器
 */
@RestController
@RequestMapping("/note/category")
public class NoteCategoryController {

    @Autowired
    private NoteCategoryService noteCategoryService;

    /**
     * 添加分类
     */
    @PostMapping("/add")
    public Result<Long> add(
            HttpServletRequest request,
            @RequestBody NoteCategory category) {
        Long userId = (Long) request.getAttribute("userId");
        category.setUserId(userId);
        Long id = noteCategoryService.add(category);
        return Result.success(id);
    }

    /**
     * 修改分类
     */
    @PostMapping("/update")
    public Result<Void> update(
            HttpServletRequest request,
            @RequestBody NoteCategory category) {
        Long userId = (Long) request.getAttribute("userId");
        category.setUserId(userId);
        noteCategoryService.update(category);
        return Result.success();
    }

    /**
     * 删除分类
     */
    @PostMapping("/delete")
    public Result<Void> delete(
            HttpServletRequest request,
            @NotNull(message = "ID不能为空") @RequestParam Long id) {
        Long userId = (Long) request.getAttribute("userId");
        noteCategoryService.delete(id, userId);
        return Result.success();
    }

    /**
     * 获取分类详情
     */
    @GetMapping("/detail")
    public Result<NoteCategory> detail(
            HttpServletRequest request,
            @NotNull(message = "ID不能为空") @RequestParam Long id) {
        Long userId = (Long) request.getAttribute("userId");
        NoteCategory detail = noteCategoryService.getDetail(id, userId);
        return Result.success(detail);
    }

    /**
     * 获取用户的所有分类
     */
    @GetMapping("/list")
    public Result<List<NoteCategory>> list(HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        List<NoteCategory> list = noteCategoryService.listByUserId(userId);
        return Result.success(list);
    }

    /**
     * 分页查询分类
     */
    @GetMapping("/page")
    public Result<Page<NoteCategory>> page(
            HttpServletRequest request,
            @RequestParam(required = false) String name,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        Long userId = (Long) request.getAttribute("userId");
        Page<NoteCategory> page = noteCategoryService.page(userId, name, pageNum, pageSize);
        return Result.success(page);
    }
} 